package com.anzia.vueblog.blog.controller;


import cn.hutool.core.bean.BeanUtil;
import com.anzia.vueblog.blog.entity.MBlog;
import com.anzia.vueblog.blog.service.MBlogService;
import com.anzia.vueblog.common.lang.Result;
import com.anzia.vueblog.util.ShiroUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Anzia.
 * @since 2021-04-24
 */
@RestController
public class MBlogController {

    @Autowired
    MBlogService mBlogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 5);
        IPage<MBlog> pageData = mBlogService.page(page, new QueryWrapper<MBlog>().orderByDesc("created"));

        return Result.success(pageData);
    }

    @GetMapping("/blogs/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        MBlog mBlog = mBlogService.getById(id);
        Assert.notNull(mBlog, "该博客已被删除");

        return Result.success(mBlog);
    }

    @RequiresAuthentication
    @PostMapping("/blogs/edit")
    public Result edit(@Validated @RequestBody MBlog mBlog) {

        MBlog temp = null;

        if (mBlog.getId() != null) {
            temp = mBlogService.getById(mBlog.getId());
            // 只能编辑文章
            Assert.isTrue(temp.getUserId() == ShiroUtil.getProfile().getId(), "没有权限编辑");
        } else {
            temp = new MBlog();
            temp.setUserId((ShiroUtil.getProfile().getId()));
            temp.setCreated(new Date());
            temp.setStatus(0);
        }

        BeanUtil.copyProperties(mBlog,temp,"id","userId","created","status");
        mBlogService.saveOrUpdate(temp);



        return Result.success(null);
    }

}

